﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class CustomAttributeRule : ILRule<CustomAttributeHandle>
    {
        [ILInfo]
        public EntityHandle Parent { get; }

        [ILInfo(true)]
        public EntityHandle Constructor { get; }

        public byte[] Value { get; }

        public CustomAttributeRule(
            EntityHandle parent,
            EntityHandle constructor,
            byte[] value)
            : base()
        {
            Parent = parent;
            Constructor = constructor;
            Value = value;
        }

        public CustomAttributeRule(MetadataReader reader, CustomAttributeHandle customAttributeHandle)
            : base(reader)
        {
            CustomAttribute customAttribute = reader.GetCustomAttribute(customAttributeHandle);
            Constructor = customAttribute.Constructor;
            Parent = customAttribute.Parent;
            Value = reader.GetBlobBytes(customAttribute.Value);
        }

        public override CustomAttributeHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddCustomAttribute(
                parent: Parent,
                constructor: Constructor,
                value: Value == null ? default : builder.GetOrAddBlob(Value));
        }
    }
}